﻿Public Class CheckEAN

    Public Shared Function BerechneEanChecksum(EAN As String) As Boolean
        Select Case EAN.Length
            Case >= 12
                Return EAN.EndsWith(Checksum_ean13(EAN).ToString)
            Case <= 8
                Return EAN.EndsWith(Checksum_ean8(EAN).ToString)
            Case Else
                Return False
        End Select
    End Function




    Private Shared Function Checksum_ean8(data As [String]) As Integer
        ' Test string for correct length
        If data.Length <> 7 AndAlso data.Length <> 8 Then
            Return -1
        End If

        ' Test string for being numeric
        For i As Integer = 0 To data.Length - 1
            If Asc(data(i)) < &H30 OrElse Asc(data(i)) > &H39 Then
                Return -1
            End If
        Next

        Dim sum As Integer = 0

        For i As Integer = 6 To 0 Step -1
            Dim digit As Integer = Asc(data(i)) - &H30
            If (i And 1) = 0 Then
                sum += digit
            Else
                sum += digit * 3
            End If
        Next
        Dim [mod] As Integer = sum Mod 10
        Return If([mod] = 0, 0, 10 - [mod])
    End Function



    Private Shared Function Checksum_ean13(data As [String]) As Integer
        ' Test string for correct length
        If data.Length <> 12 AndAlso data.Length <> 13 Then
            Return -1
        End If

        ' Test string for being numeric
        For i As Integer = 0 To data.Length - 1
            If Asc(data(i)) < &H30 OrElse Asc(data(i)) > &H39 Then
                Return -1
            End If
        Next

        Dim sum As Integer = 0

        For i As Integer = 11 To 0 Step -1
            Dim digit As Integer = Asc(data(i)) - &H30
            If (i And 1) = 0 Then
                sum += digit
            Else
                sum += digit * 3
            End If

        Next
        Dim [mod] As Integer = sum Mod 10
        Return If([mod] = 0, 0, 10 - [mod])
    End Function



End Class
